<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { NButton, NDrawer, NDrawerContent, NSpace, NTabPane, NTabs } from 'naive-ui';
import { useForm } from '@sa/alova/client';
import { generateTemplateByAI } from '@/service/api/cms';
import StyleConfigurator from './style-configurator.vue';
import TemplatePreview from './template-preview.vue';
import PromptConfigurator from './prompt-configurator.vue';

defineOptions({
  name: 'TemplateAIGenerateDrawer'
});

interface Props {
  /** the template data to generate for */
  templateData?: Api.Model | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

interface StyleConfig {
  theme: {
    primaryColor: string;
    secondaryColor: string;
    accentColor: string;
    backgroundColor: string;
    surfaceColor: string;
  };
  typography: {
    fontFamily: string;
    baseFontSize: number;
    headingScale: number;
    lineHeight: number;
    letterSpacing: number;
  };
  layout: {
    borderRadius: number;
    spacing: number;
    maxWidth: number;
    gridGap: number;
  };
  components: {
    buttonStyle: 'filled' | 'outlined' | 'ghost';
    cardElevation: number;
    inputStyle: 'underline' | 'outline' | 'filled';
  };
}

interface AIGenerate {
  prompt: string;
  businessData: string;
  config: StyleConfig;
  contentType: 'landing' | 'product' | 'blog';
  templateId: number;
}

const styleConfig = reactive<StyleConfig>({
  theme: {
    primaryColor: '#3B82F6',
    secondaryColor: '#10B981',
    accentColor: '#F59E0B',
    backgroundColor: '#FFFFFF',
    surfaceColor: '#F8FAFC'
  },
  typography: {
    fontFamily: 'Inter',
    baseFontSize: 16,
    headingScale: 1.25,
    lineHeight: 1.5,
    letterSpacing: 0
  },
  layout: {
    borderRadius: 8,
    spacing: 16,
    maxWidth: 1200,
    gridGap: 24
  },
  components: {
    buttonStyle: 'filled',
    cardElevation: 2,
    inputStyle: 'outline'
  }
});

const aiPrompt = reactive<AIGenerate>({
  prompt: '',
  businessData: '',
  config: styleConfig,
  contentType: 'landing',
  templateId: 0
});

const currentContentType = ref<'landing' | 'product' | 'blog'>('landing');
const previewDevice = ref<'mobile' | 'tablet' | 'desktop'>('desktop');
const isDarkMode = ref(false);
const isGenerating = ref(false);
const generatedTemplate = ref('');

const { send: generateTemplate } = useForm(() => generateTemplateByAI(aiPrompt), {
  initialForm: aiPrompt,
  resetAfterSubmitting: false
});

const presetStyles = [
  { name: '现代简约', value: 'modern' },
  { name: '商务专业', value: 'business' },
  { name: '创意艺术', value: 'creative' },
  { name: '科技感', value: 'tech' },
  { name: '温暖亲和', value: 'warm' }
];

function applyPresetStyle(preset: string) {
  const presets: Record<string, StyleConfig> = {
    modern: {
      theme: {
        primaryColor: '#3B82F6',
        secondaryColor: '#10B981',
        accentColor: '#F59E0B',
        backgroundColor: '#FFFFFF',
        surfaceColor: '#F8FAFC'
      },
      typography: {
        fontFamily: 'Inter',
        baseFontSize: 16,
        headingScale: 1.25,
        lineHeight: 1.6,
        letterSpacing: 0
      },
      layout: {
        borderRadius: 12,
        spacing: 24,
        maxWidth: 1280,
        gridGap: 32
      },
      components: {
        buttonStyle: 'filled' as const,
        cardElevation: 3,
        inputStyle: 'outline' as const
      }
    },
    business: {
      theme: {
        primaryColor: '#1E40AF',
        secondaryColor: '#374151',
        accentColor: '#DC2626',
        backgroundColor: '#FFFFFF',
        surfaceColor: '#F9FAFB'
      },
      typography: {
        fontFamily: 'Arial',
        baseFontSize: 14,
        headingScale: 1.2,
        lineHeight: 1.4,
        letterSpacing: 0.5
      },
      layout: {
        borderRadius: 4,
        spacing: 12,
        maxWidth: 1140,
        gridGap: 16
      },
      components: {
        buttonStyle: 'outlined' as const,
        cardElevation: 1,
        inputStyle: 'filled' as const
      }
    },
    creative: {
      theme: {
        primaryColor: '#EC4899',
        secondaryColor: '#8B5CF6',
        accentColor: '#F59E0B',
        backgroundColor: '#FDF2F8',
        surfaceColor: '#FCE7F3'
      },
      typography: {
        fontFamily: 'Georgia',
        baseFontSize: 18,
        headingScale: 1.4,
        lineHeight: 1.8,
        letterSpacing: 1
      },
      layout: {
        borderRadius: 20,
        spacing: 20,
        maxWidth: 1000,
        gridGap: 40
      },
      components: {
        buttonStyle: 'ghost' as const,
        cardElevation: 4,
        inputStyle: 'underline' as const
      }
    },
    tech: {
      theme: {
        primaryColor: '#06B6D4',
        secondaryColor: '#3B82F6',
        accentColor: '#10B981',
        backgroundColor: '#0F172A',
        surfaceColor: '#1E293B'
      },
      typography: {
        fontFamily: 'Monaco',
        baseFontSize: 16,
        headingScale: 1.3,
        lineHeight: 1.6,
        letterSpacing: 0.5
      },
      layout: {
        borderRadius: 6,
        spacing: 16,
        maxWidth: 1400,
        gridGap: 24
      },
      components: {
        buttonStyle: 'filled' as const,
        cardElevation: 2,
        inputStyle: 'outline' as const
      }
    },
    warm: {
      theme: {
        primaryColor: '#F97316',
        secondaryColor: '#EF4444',
        accentColor: '#FBBF24',
        backgroundColor: '#FFFBEB',
        surfaceColor: '#FEF3C7'
      },
      typography: {
        fontFamily: 'Times New Roman',
        baseFontSize: 17,
        headingScale: 1.35,
        lineHeight: 1.7,
        letterSpacing: 0.3
      },
      layout: {
        borderRadius: 16,
        spacing: 18,
        maxWidth: 1100,
        gridGap: 28
      },
      components: {
        buttonStyle: 'filled' as const,
        cardElevation: 3,
        inputStyle: 'filled' as const
      }
    }
  };

  Object.assign(styleConfig, presets[preset] || presets.modern);
}

function randomizeStyle() {
  const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899', '#06B6D4', '#F97316'];
  const fonts = ['Inter', 'Arial', 'Georgia', 'Monaco', 'Times New Roman', 'Helvetica'];
  const buttonStyles = ['filled', 'outlined', 'ghost'] as const;
  const inputStyles = ['underline', 'outline', 'filled'] as const;

  styleConfig.theme.primaryColor = colors[Math.floor(Math.random() * colors.length)];
  styleConfig.theme.secondaryColor = colors[Math.floor(Math.random() * colors.length)];
  styleConfig.theme.accentColor = colors[Math.floor(Math.random() * colors.length)];
  styleConfig.theme.backgroundColor = Math.random() > 0.5 ? '#FFFFFF' : '#F8FAFC';
  styleConfig.theme.surfaceColor = Math.random() > 0.5 ? '#F8FAFC' : '#FFFFFF';

  styleConfig.typography.fontFamily = fonts[Math.floor(Math.random() * fonts.length)];
  styleConfig.typography.baseFontSize = 14 + Math.floor(Math.random() * 8);
  styleConfig.typography.headingScale = 1.1 + Math.random() * 0.5;
  styleConfig.typography.lineHeight = 1.2 + Math.random() * 0.8;
  styleConfig.typography.letterSpacing = Math.floor(Math.random() * 3);

  styleConfig.layout.borderRadius = 4 + Math.floor(Math.random() * 20);
  styleConfig.layout.spacing = 8 + Math.floor(Math.random() * 24);
  styleConfig.layout.maxWidth = 900 + Math.floor(Math.random() * 600);
  styleConfig.layout.gridGap = 12 + Math.floor(Math.random() * 36);

  styleConfig.components.buttonStyle = buttonStyles[Math.floor(Math.random() * buttonStyles.length)];
  styleConfig.components.cardElevation = 1 + Math.floor(Math.random() * 5);
  styleConfig.components.inputStyle = inputStyles[Math.floor(Math.random() * inputStyles.length)];
}

async function handleGenerateTemplate() {
  try {
    isGenerating.value = true;
    aiPrompt.config = { ...styleConfig };
    aiPrompt.contentType = currentContentType.value;
    aiPrompt.templateId = props.templateData?.id as number;

    const requestData = {
      ...aiPrompt,
      templateId: props.templateData?.id
    };

    // Add template-specific context if available
    if (props.templateData) {
      requestData.prompt = `基于模板 "${props.templateData.name}" (${props.templateData.code}) 生成内容: ${aiPrompt.prompt}`;
    }

    const result = await generateTemplate(requestData);
    if (result) {
      // generatedTemplate.value = result.template || '';
      window.$message?.success('模板正在生成，请稍等片刻');
      emit('submitted');
      visible.value = false;
    }
  } catch {
    window.$message?.error('模板生成失败，请重试');
  } finally {
    isGenerating.value = false;
  }
}

// function saveConfiguration() {
//   const config = {
//     styleConfig,
//     aiPrompt,
//     timestamp: new Date().toISOString()
//   };
//   localStorage.setItem('ai-template-config', JSON.stringify(config));
//   window.$message?.success('配置已保存到本地');
// }

// function loadConfiguration() {
//   const saved = localStorage.getItem('ai-template-config');
//   if (saved) {
//     try {
//       const config = JSON.parse(saved);
//       Object.assign(styleConfig, config.styleConfig);
//       Object.assign(aiPrompt, config.aiPrompt);
//       window.$message?.success('配置已加载');
//     } catch {
//       window.$message?.error('配置加载失败');
//     }
//   }
// }

// Initialize with template data if available
watch(
  () => props.templateData,
  newData => {
    if (newData) {
      // Only update the prompt prefix if it's still the default bootstrap prompt
      const defaultBootstrapPrompt = `我会给你一个文件，分析内容，并将其转化为美观漂亮的中文可视化网页：`;
      if (aiPrompt.prompt.startsWith(defaultBootstrapPrompt)) {
        aiPrompt.prompt = `基于模板 "${newData.name}" (${newData.code}) 生成内容: ${aiPrompt.prompt}`;
      }
    }
  },
  { immediate: true }
);

// Watch for style changes to update preview
watch(
  styleConfig,
  () => {
    // Preview will be automatically updated via reactive binding
  },
  { deep: true }
);
</script>

<template>
  <NDrawer v-model:show="visible" width="100vw" height="100vh" placement="right" :mask-closable="false">
    <NDrawerContent
      :title="`AI生成模板 - ${templateData?.name || '新模板'}`"
      :native-scrollbar="false"
      closable
      class="h-full"
    >
      <template #footer>
        <NSpace justify="end">
          <NButton type="primary" :loading="isGenerating" @click="handleGenerateTemplate">生成模板</NButton>
        </NSpace>
      </template>

      <div class="h-full flex gap-16px">
        <!-- Left Panel - Preview -->
        <div class="flex flex-col flex-1 gap-16px">
          <div class="flex-1">
            <TemplatePreview
              :style-config="styleConfig"
              :content-type="currentContentType"
              :device="previewDevice"
              :is-dark="isDarkMode"
              :generated-template="generatedTemplate"
              @update:content-type="currentContentType = $event"
              @update:device="previewDevice = $event"
              @update:is-dark="isDarkMode = $event"
            />
          </div>
        </div>

        <!-- Right Panel - Configuration with Tabs -->
        <div class="w-380px flex-shrink-0">
          <NTabs type="line" animated>
            <NTabPane name="style" tab="样式配置">
              <div class="configuration-panel">
                <StyleConfigurator
                  :style-config="styleConfig"
                  :preset-styles="presetStyles"
                  @update:style-config="Object.assign(styleConfig, $event)"
                  @apply-preset="applyPresetStyle"
                  @randomize="randomizeStyle"
                />
              </div>
            </NTabPane>
            <NTabPane name="prompt" tab="提示词配置">
              <div class="configuration-panel">
                <PromptConfigurator :prompt="aiPrompt" @update:prompt="Object.assign(aiPrompt, $event)" />
              </div>
            </NTabPane>
          </NTabs>
        </div>
      </div>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
:deep(.n-drawer-content) {
  height: 100vh;
}

:deep(.n-drawer-body-content-wrapper) {
  height: calc(100vh - 60px);
}

.configuration-panel {
  height: calc(100vh - 200px);
  overflow-y: auto;
  padding: 16px 0;
}

:deep(.n-tabs-nav) {
  margin-bottom: 16px;
}

:deep(.n-tab-pane) {
  padding: 0;
}

.content-type-select {
  width: 120px;
}

.device-select {
  width: 100px;
}

:deep(.n-tabs-content) {
  height: calc(100vh - 200px);
}
</style>
